
from django.views import View
from django.http import HttpResponse
from django_redis import get_redis_connection
from i_home.libs.captcha.captcha import captcha
import logging
logger = logging.getLogger('django')
import random
from django import http
import json
from celery_tasks.sms.tasks import ccp_send_sms_code


class ImageCodeView(View):
    '''返回图形验证码类视图'''

    def get(self, request):
        # 1.调用工具类captch生成图形验证码
        text, image = captcha.generate_captcha()
        print(text)

        cur = request.GET.get('cur')
        pre = request.GET.get('pre')
        #链接redis，获取连接对象
        redis_conn = get_redis_connection('verify_code')

        #利用连接对象，保存数据到redis，使用setex函数
        redis_conn.setex('img_%s' % cur, 300, text)

        #返回图片
        return HttpResponse(image,
                            content_type='image/jpg')


class SMSCodeView(View):
    '''短信验证码'''

    def post(self,reqeust):

        #1.接收参数
        dict = json.loads(reqeust.body.decode())
        text = dict.get('text')
        id = dict.get('id')
        mobile = dict.get('mobile')

        # 3.创建连接到redis对象
        redis_coon = get_redis_connection('verify_code')

        # 进入函数后，获取储存在redis中的数据
        send_flag = redis_coon.get('send_flag_%s' % mobile)

        #查看数据是否存在
        if send_flag:
            return http.JsonResponse({'errno':4201,
                                      'errmsg':'REQERR'})

        #2.效验参数
        if not all([text, id]):
            return http.JsonResponse({'errno': 4103,
                                      'errmsg': 'PARAMERR'})

        #4提取图形验证码
        image_code_server = redis_coon.get('img_%s' % id)
        if image_code_server is None:
            return http.JsonResponse({'errno': 4002,
                                      'errmsg': 'NODATA'})


        #5.删除图形验证码
        try:
            redis_coon.delete('img_%s' % id)
        except Exception as e:
            logger.error(e)


        #6对比图形验证码
        #byte转字符串
        image_code_server = image_code_server.decode()
        #转小写后比较
        if text.lower() != image_code_server.lower():
            return http.JsonResponse({'errno': 4004,
                                      'errmsg': 'DATAERR'})

        #7生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)

        #创建管道对象
        p1 = redis_coon.pipeline()

        #8保存短信验证码
        p1.setex('sms_%s' % mobile, 300, sms_code)

        #往redis中写入数据
        p1.setex('send_flag_%s' % mobile, 60 ,1)

        #执行管道
        p1.execute()

        #9.发送短信验证码
        #短信模板
        # CCP().send_template_sms(mobile,[sms_code, 5], 1)

        ccp_send_sms_code.delay(mobile, sms_code)

        #10响应结果
        return http.JsonResponse({'errno': 0,
                                  'errmsg': '发送成功'})


